<template>
  <div class="skill-container">
    <!-- 顶部标签栏 -->
    <div class="tab-bar">
      <div 
        class="tab-item" 
        :class="{active: activeTab === 'learned'}"
        @click="switchTab('learned')"
      >
        已学会
      </div>
      <div 
        class="tab-item" 
        :class="{active: activeTab === 'available'}"
        @click="switchTab('available')"
      >
        可学习
      </div>
      <div 
        class="tab-item" 
        :class="{active: activeTab === 'scrolls'}"
        @click="switchTab('scrolls')"
      >
        武学残卷
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar" v-if="activeTab === 'learned'">
      <div 
        class="filter-item" 
        :class="{active: activeFilter === 'all'}"
        @click="switchFilter('all')"
      >
        全部
      </div>
      <div 
        class="filter-item" 
        :class="{active: activeFilter === 'active'}"
        @click="switchFilter('active')"
      >
        主动
      </div>
      <div 
        class="filter-item" 
        :class="{active: activeFilter === 'passive'}"
        @click="switchFilter('passive')"
      >
        被动
      </div>
    </div>

    <!-- 武学列表 -->
    <div class="skill-list">
      <!-- 已学会的武学 -->
      <div v-if="activeTab === 'learned'" class="learned-skills">
        <div 
          v-for="skill in filteredLearnedSkills" 
          :key="skill.id"
          class="skill-card"
          @click="showSkillDetail(skill)"
        >
          <div class="skill-icon">
            <img :src="getSkillIcon(skill.type)" :alt="skill.name" />
          </div>
          <div class="skill-info">
            <div class="skill-name">{{ skill.name }}</div>
            <div class="skill-level">Lv.{{ skill.level }}</div>
            <div class="skill-type">{{ getSkillTypeName(skill.type) }}</div>
          </div>
          <div class="skill-stats">
            <div class="stat-item">
              <span class="stat-label">威力</span>
              <span class="stat-value">{{ skill.power || '-' }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">消耗</span>
              <span class="stat-value">{{ skill.cost || '-' }}</span>
            </div>
          </div>
          <div class="skill-actions">
            <button 
              v-if="skill.canUpgrade"
              class="upgrade-btn"
              @click.stop="upgradeSkill(skill)"
            >
              升级
            </button>
            <button 
              v-if="skill.type === 'active'"
              class="equip-btn"
              :class="{equipped: skill.isEquipped}"
              @click.stop="toggleEquipSkill(skill)"
            >
              {{ skill.isEquipped ? '卸下' : '装备' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 可学习的武学 -->
      <div v-if="activeTab === 'available'" class="available-skills">
        <div 
          v-for="skill in availableSkills" 
          :key="skill.id"
          class="skill-card available"
          @click="showSkillDetail(skill)"
        >
          <div class="skill-icon">
            <img :src="getSkillIcon(skill.type)" :alt="skill.name" />
          </div>
          <div class="skill-info">
            <div class="skill-name">{{ skill.name }}</div>
            <div class="skill-type">{{ getSkillTypeName(skill.type) }}</div>
            <div class="skill-requirements">
              <div v-for="req in skill.requirements" :key="req.type" class="requirement">
                <span :class="{met: req.met}">{{ req.description }}</span>
              </div>
            </div>
          </div>
          <div class="skill-actions">
            <button 
              class="learn-btn"
              @click.stop="learnSkill(skill)"
              :disabled="!canLearnSkill(skill)"
            >
              学习
            </button>
          </div>
        </div>
      </div>

      <!-- 武学残卷 -->
      <div v-if="activeTab === 'scrolls'" class="skill-scrolls">
        <div 
          v-for="scroll in skillScrolls" 
          :key="scroll.id"
          class="scroll-card"
          @click="showScrollDetail(scroll)"
        >
          <div class="scroll-icon">
            <img :src="getScrollIcon(scroll.rarity)" :alt="scroll.name" />
          </div>
          <div class="scroll-info">
            <div class="scroll-name">{{ scroll.name }}</div>
            <div class="scroll-rarity">{{ getRarityName(scroll.rarity) }}</div>
            <div class="scroll-count">数量: {{ scroll.count }}</div>
          </div>
          <div class="scroll-actions">
            <button 
              class="use-btn"
              @click.stop="useScroll(scroll)"
              :disabled="scroll.count <= 0"
            >
              使用
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="showEmptyState" class="empty-state">
      <div class="empty-icon">📜</div>
      <div class="empty-text">{{ getEmptyText() }}</div>
    </div>

    <!-- 武学详情弹窗 -->
    <div v-if="showDetailModal" class="skill-detail-modal" @click="closeDetailModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ selectedSkill.name }}</h3>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </div>
        <div class="modal-body">
          <div class="skill-detail-info">
            <div class="detail-row">
              <span class="label">类型:</span>
              <span class="value">{{ getSkillTypeName(selectedSkill.type) }}</span>
            </div>
            <div class="detail-row" v-if="selectedSkill.level">
              <span class="label">等级:</span>
              <span class="value">Lv.{{ selectedSkill.level }}</span>
            </div>
            <div class="detail-row" v-if="selectedSkill.power">
              <span class="label">威力:</span>
              <span class="value">{{ selectedSkill.power }}</span>
            </div>
            <div class="detail-row" v-if="selectedSkill.cost">
              <span class="label">消耗:</span>
              <span class="value">{{ selectedSkill.cost }}</span>
            </div>
            <div class="detail-row">
              <span class="label">描述:</span>
              <span class="value">{{ selectedSkill.description }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 全局底部导航栏 -->
    <CustomTabBar />
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'learned', // learned, available, scrolls
      activeFilter: 'all', // all, active, passive
      playerLevel: 25, // 玩家等级，用于判断槽位解锁
      skills: [], // 已学会的武学列表
      equippedSkills: [null, null, null, null], // 装备的武学，4个槽位
      skillScrolls: [], // 武学残卷列表
      loading: false,
      showDetailModal: false, // 控制详情弹窗显示
      selectedSkill: null // 当前选中的武学
    }
  },
  
  computed: {
    // 根据筛选条件过滤武学
    filteredSkills() {
      if (this.activeFilter === 'all') {
        return this.skills;
      }
      return this.skills.filter(skill => skill.type === this.activeFilter);
    },
    
    // 过滤已学会的武学（用于已学会标签页）
    filteredLearnedSkills() {
      if (this.activeFilter === 'all') {
        return this.skills;
      }
      return this.skills.filter(skill => skill.type === this.activeFilter);
    },
    
    // 是否显示空状态
    showEmptyState() {
      if (this.activeTab === 'learned') {
        return this.filteredLearnedSkills.length === 0 && !this.loading;
      } else if (this.activeTab === 'scrolls') {
        return this.skillScrolls.length === 0 && !this.loading;
      }
      return false;
    }
  },
  
  onLoad() {
    this.loadPlayerSkills();
    this.loadSkillScrolls();
  },
  
  methods: {
    // 切换标签
    switchTab(tab) {
      this.activeTab = tab;
      if (tab === 'learned') {
        this.loadPlayerSkills();
      } else if (tab === 'scrolls') {
        this.loadSkillScrolls();
      }
    },
    
    // 切换筛选
    switchFilter(filter) {
      this.activeFilter = filter;
    },
    
    // 判断槽位是否解锁
    isSlotUnlocked(index) {
      const unlockLevels = [1, 10, 30, 50];
      return this.playerLevel >= unlockLevels[index];
    },
    
    // 获取槽位解锁等级
    getUnlockLevel(index) {
      const unlockLevels = [1, 10, 30, 50];
      return unlockLevels[index];
    },
    
    // 处理槽位点击
    handleSlotClick(index) {
      if (!this.isSlotUnlocked(index)) {
        uni.showToast({
          title: `${this.getUnlockLevel(index)}级解锁该槽位`,
          icon: 'none'
        });
        return;
      }
      
      // 打开武学选择页面
      uni.navigateTo({
        url: `/pages/skill/equip?slot=${index}`
      });
    },
    
    // 查看武学详情
    viewSkillDetail(skill) {
      uni.navigateTo({
        url: `/pages/skill/detail?id=${skill.id}`
      });
    },
    
    // 获取武学图标路径
    getSkillIcon(icon) {
      return `/static/icons/skills/${icon}`;
    },
    
    // 获取类型文本
    getTypeText(type) {
      return type === 'active' ? '主动' : '被动';
    },
    
    // 加载玩家武学
    async loadPlayerSkills() {
      this.loading = true;
      try {
        const res = await uni.request({
          url: `${this.$config.baseUrl}/api/player/skills`,
          method: 'GET',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (res.data.code === 200) {
          this.skills = res.data.data.skills || [];
          this.equippedSkills = res.data.data.equippedSkills || [null, null, null, null];
        } else {
          uni.showToast({
            title: res.data.message || '获取武学列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载武学列表失败:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 加载武学残卷
    async loadSkillScrolls() {
      try {
        const res = await uni.request({
          url: `${this.$config.baseUrl}/api/player/scrolls`,
          method: 'GET',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (res.data.code === 200) {
          this.skillScrolls = res.data.data || [];
        }
      } catch (error) {
        console.error('加载残卷列表失败:', error);
      }
    },
    
    // 显示武学详情
    showSkillDetail(skill) {
      this.selectedSkill = skill;
      this.showDetailModal = true;
    },
    
    // 关闭详情弹窗
    closeDetailModal() {
      this.showDetailModal = false;
      this.selectedSkill = null;
    },
    
    // 获取空状态文本
    getEmptyText() {
      if (this.activeTab === 'learned') {
        return '暂无已学会的武学';
      } else if (this.activeTab === 'scrolls') {
        return '暂无武学残卷';
      }
      return '暂无数据';
    },
    
    // 获取武学类型名称
    getSkillTypeName(type) {
      const typeMap = {
        'active': '主动技能',
        'passive': '被动技能',
        'internal': '内功心法',
        'sword': '剑法',
        'palm': '掌法',
        'fist': '拳法',
        'leg': '腿法',
        'finger': '指法',
        'hidden': '暗器'
      };
      return typeMap[type] || '未知类型';
    },
    
    // 升级武学
    async upgradeSkill(skill) {
      try {
        const res = await uni.request({
          url: `${this.$config.baseUrl}/api/player/skills/${skill.id}/upgrade`,
          method: 'POST',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (res.data.code === 200) {
          uni.showToast({
            title: '升级成功',
            icon: 'success'
          });
          this.loadPlayerSkills(); // 重新加载武学列表
        } else {
          uni.showToast({
            title: res.data.message || '升级失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('升级武学失败:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    },
    
    // 装备/卸下武学
    async toggleEquipSkill(skill) {
      try {
        const action = skill.isEquipped ? 'unequip' : 'equip';
        const res = await uni.request({
          url: `${this.$config.baseUrl}/api/player/skills/${skill.id}/${action}`,
          method: 'POST',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (res.data.code === 200) {
          uni.showToast({
            title: skill.isEquipped ? '卸下成功' : '装备成功',
            icon: 'success'
          });
          this.loadPlayerSkills(); // 重新加载武学列表
        } else {
          uni.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('装备武学失败:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    },
    
    // 使用武学残卷
    async useScroll(scroll) {
      try {
        const res = await uni.request({
          url: `${this.$config.baseUrl}/api/player/scrolls/${scroll.id}/use`,
          method: 'POST',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (res.data.code === 200) {
          uni.showToast({
            title: '使用成功',
            icon: 'success'
          });
          this.loadSkillScrolls(); // 重新加载残卷列表
          this.loadPlayerSkills(); // 重新加载武学列表
        } else {
          uni.showToast({
            title: res.data.message || '使用失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('使用残卷失败:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style scoped>
.skill-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 标签栏样式 */
.tab-bar {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 16px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.tab-item.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: bold;
}

/* 筛选栏样式 */
.filter-bar {
  display: flex;
  background-color: #fff;
  padding: 10px 15px;
  border-bottom: 1px solid #e0e0e0;
}

.filter-item {
  padding: 8px 16px;
  margin-right: 10px;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  background-color: #f0f0f0;
  transition: all 0.3s;
}

.filter-item.active {
  color: #fff;
  background-color: #1890ff;
}

/* 装备槽位样式 */
.equip-slots {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.slots-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.slots-container {
  display: flex;
  justify-content: space-between;
}

.slot-item {
  width: 22%;
  aspect-ratio: 1;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.slot-item.unlocked {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.slot-item.equipped {
  border: 2px solid #52c41a;
  background-color: #f6ffed;
}

.equipped-skill {
  text-align: center;
}

.equipped-skill .skill-icon {
  width: 30px;
  height: 30px;
  margin-bottom: 5px;
}

.equipped-skill .skill-name {
  font-size: 12px;
  color: #333;
  margin-bottom: 2px;
}

.equipped-skill .skill-level {
  font-size: 10px;
  color: #666;
}

.empty-slot {
  text-align: center;
  color: #1890ff;
}

.plus-icon {
  font-size: 24px;
  display: block;
  margin-bottom: 5px;
}

.slot-text {
  font-size: 10px;
}

.locked-slot {
  text-align: center;
  color: #999;
}

.lock-icon {
  font-size: 20px;
  display: block;
  margin-bottom: 5px;
}

.unlock-text {
  font-size: 10px;
}

/* 武学列表样式 */
.skill-list {
  flex: 1;
  padding: 10px;
}

.skill-item {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.skill-info {
  display: flex;
  align-items: flex-start;
}

.skill-icon {
  width: 50px;
  height: 50px;
  margin-right: 15px;
  border-radius: 8px;
}

.skill-details {
  flex: 1;
}

.skill-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.skill-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}

.skill-level {
  font-size: 12px;
  color: #666;
  margin-right: 10px;
}

.skill-type {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  color: #fff;
}

.skill-type.active {
  background-color: #ff4d4f;
}

.skill-type.passive {
  background-color: #52c41a;
}

.skill-description {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8px;
}

.skill-status {
  display: flex;
  gap: 8px;
}

.equipped-badge {
  padding: 2px 8px;
  background-color: #52c41a;
  color: #fff;
  font-size: 10px;
  border-radius: 10px;
}

.upgrade-badge {
  padding: 2px 8px;
  background-color: #faad14;
  color: #fff;
  font-size: 10px;
  border-radius: 10px;
}

/* 残卷列表样式 */
.scroll-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.scroll-item .skill-icon {
  width: 40px;
  height: 40px;
  margin-right: 15px;
}

.scroll-info {
  flex: 1;
}

.scroll-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.scroll-count {
  font-size: 14px;
  color: #666;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 50px 20px;
}

.empty-text {
  font-size: 16px;
  color: #999;
}
</style>